package com.fierce.cloud.security.service;

import com.fierce.cloud.ota.dao.UserRoleMapper;
import com.fierce.cloud.ota.model.Role;
import com.fierce.cloud.ota.model.User;
import com.fierce.cloud.ota.model.UserRole;
import com.fierce.cloud.ota.service.UserService;
import com.fierce.cloud.security.common.utils.CurrentUserUtils;
import com.fierce.cloud.security.common.utils.JwtTokenUtils;
import com.fierce.cloud.security.entity.JwtUser;
import com.fierce.cloud.security.entity.LoginRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author: Fierce
 * @Date: 2020/12/3 14:14
 */
@Service
public class AuthService {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CurrentUserUtils currentUserUtils;

    @Autowired
    UserRoleMapper userRoleMapper;

    public String getToken(LoginRequest loginRequest) {
        User user = Optional.ofNullable(userService.findByUsername(loginRequest.getUsername())).orElse(new User());
        if (!userService.check(loginRequest.getPassword(), user.getPassword())) {
            throw new BadCredentialsException("The user name or password is not correct.");
        }
        user.setRoles(userRoleMapper.selectRolesByUserId(user.getId()));
        JwtUser jwtUser = new JwtUser(user);
        List<String> authorities = jwtUser.getAuthorities()
                .stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        String token = JwtTokenUtils.createToken(user.getUsername(), user.getId().toString(), authorities, loginRequest.getRememberMe());
        if (loginRequest.getRememberMe()) {
            stringRedisTemplate.opsForValue().set(user.getId().toString(), token);
        } else {
            stringRedisTemplate.opsForValue().set(user.getId().toString(), token, 30, TimeUnit.MINUTES);
        }
        return token;
    }

    public void deleteTokenFromRedis() {
        Optional.ofNullable(currentUserUtils.getCurrentUser()).orElseThrow(() -> new UsernameNotFoundException("找不到用户"));
        System.out.println(currentUserUtils.getCurrentUser().getId().toString());
        stringRedisTemplate.delete(currentUserUtils.getCurrentUser().getId().toString());
    }
}
